﻿using FNN.Models;
using LiveCharts;
using LiveCharts.Configurations;
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;

namespace GraphicFNN
{
    /// <summary>
    /// Логика взаимодействия для ChartWindow.xaml
    /// </summary>
    public partial class ChartWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(String name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        public void CatchIterationChanged(int iterationNumber)
        {
            Dispatcher.Invoke(() =>
            {
                LblIterationNumber.Content = iterationNumber;
            });
        }
             
        public void CatchResultsImproved(int iterationNumber, double iterationResult)
        {
            Dispatcher.Invoke(() =>
            {
                var existElement = ChartValues.FirstOrDefault(o => o.Number == iterationNumber);
                if ((existElement != null) && (existElement.Result < iterationResult))
                {
                    existElement.Result = iterationResult;
                }

                if (existElement == null)
                {
                    if (ChartValues.Count >= 50)
                    {
                        ChartValues.Remove(ChartValues.First());
                    }
                    ChartValues.Add(new IterationModel() { Number = iterationNumber, Result = iterationResult });
                }

                var minYValue = ChartValues.Min(o => o.Result);
                var maxYValue = ChartValues.Max(o => o.Result);
                var maxXValue = ChartValues.Max(o => o.Number);
                
                XAxis.MaxValue = maxXValue + 10;
                YAxis.MinValue = minYValue - 10;
                YAxis.MaxValue = maxYValue + 10;

                OnPropertyChanged("ChartValues");
            });
        }
        
        public ChartWindow()
        {
            InitializeComponent();
            DataContext = this;

            var mapper = Mappers.Xy<IterationModel>()
                .X(model => model.Number)
                .Y(model => model.Result);

            //lets save the mapper globally.
            Charting.For<IterationModel>(mapper);

            //the values property will store our values array
            ChartValues = new ChartValues<IterationModel>();
        }

        public ChartValues<IterationModel> ChartValues { get; set; }
    }
}